<template>
  <div>
    <h1>{{id?'编辑':'新建'}}分类</h1>
    <el-form @submit.native.prevent="saveArticle" ref="form" :model="model" label-width="80px">
      <el-form-item label="上级分类">
        <el-select v-model="model.parent">
          <el-option v-for="item of parentOptions" :key="item._id" :label="item.title" :value="item._id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="名称">
        <el-input v-model="model.title"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit" @click="onSubmit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>


<script>
  export default {
    props:{
      id:{}
    },
    data() {
      return {
        model: {},
        parentOptions:[]
      }
    },
    created() {
      //this.feach()
      this.feachParentOptions()
      this.id && this.feach();
      
    },
    methods: {
      async feach(){
        const res = await this.$http.get(`rest/categories/${this.id}`)/* .then(res=>{
          console.log(res.data);
          this.model=res.data
        }) */
        this.model=res.data
      },
      onSubmit() {
        console.log('start!');
      },
      async saveArticle(){
        let res
        if (this.id) {//编辑
          res = await this.$http.put(`rest/categories/${this.id}`,this.model)
        }else{//新建
          res = await this.$http.post('rest/categories',this.model)
        } 
        this.$router.push('/categories/list')
        console.log(res.data);
        this.$message({
            message: '保存成功',
            type: 'success'
        });
      },
      async feachParentOptions(){
        const res = await this.$http.get('rest/categories')
        this.parentOptions=res.data
      },
    }
  }
</script>